using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MVC.Models.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MVC
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // 注入mvc服务
            services.AddControllersWithViews();
            // 注入数据库服务
            services.AddDbContext<LifengContext>();
            //添加授权规则为cookie 当未登录时跳转到Login.html
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(
                options => { options.LoginPath = new PathString("/Login"); } //设置登录页面为/Auth/Signin
            );
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            // 使用路由
            app.UseRouting();
            //启用身份验证，加上这句才能生效，
            //注意顺序，在 app.UseRouting();之后
            //开启认证中间件
            app.UseAuthentication();
            //开启授权中间件
            app.UseAuthorization();
            // 使用静态文件
            app.UseStaticFiles();

            // 使用终止节点添加路由配置
            app.UseEndpoints(endpoints =>
            {
                // 常规路由
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
